<?php
/**
 * Created by PhpStorm.
 * User: gabriel
 * Date: 2018/12/6
 * Time: 4:14 PM
 */
namespace Common;

class STSToken{
  public $accessKeyId;
  public $accessKeySecret;
  public $expiration;
  public $securityToken;
}

class STS{
  private $_id;

  public function __construct(string $_id) {
    $this->_id = $_id;
  }

  public function getToken(string $roleArn,int $durationSeconds=3600):STSToken{
    date_default_timezone_set("UTC");
    $rqData = [
      "Format" => "JSON",
      "Version" => "2015-04-01",
      "AccessKeyId" => \SmsConfig::ACCESSKEYID,
      "SignatureMethod" => "HMAC-SHA1",
      "SignatureVersion" => "1.0",
      "SignatureNonce" => uniqid(),
      "Timestamp" => date("Y-m-d\TH:i:s\Z "),
      "Action" => "AssumeRole",
      "RoleArn" => $roleArn,
      "DurationSeconds" => $durationSeconds,
      "RoleSessionName" => $this->_id,
    ];
    $rqData['Signature'] = self::MakeSign($rqData);
    $curl = new CURL();
    $requestUrl = "";
    foreach ($rqData as $key => $value){
      $requestUrl .= urlencode($key)."=".urlencode($value)."&";
    }
    $requestUrl = substr($requestUrl,0,-1);
    $res = $curl->get("https://sts.aliyuncs.com?".$requestUrl);
    $result = json_decode($res);
    Logger::getInstance()->info("result data ".json_encode($res));
    $token = new STSToken();
    $token->accessKeyId = $result->Credentials->AccessKeyId;
    $token->accessKeySecret = $result->Credentials->AccessKeySecret;
    $token->expiration = $result->Credentials->Expiration;
    $token->securityToken = $result->Credentials->SecurityToken;
    date_default_timezone_set("PRC");
    return $token;
  }

  public function MakeSign(array $data):string {
    ksort($data);
    $canonicalizedString = "";
    foreach ($data as $key => $value){
      $canonicalizedString .= "&".$this->pretchStr($key)."=".$this->pretchStr($value);
    }
    $canonicalizedString = substr($canonicalizedString,1);
    $stringToSign= "GET"."&%2F&".$this->pretchStr($canonicalizedString);
    $str = hash_hmac("sha1",$stringToSign,\SmsConfig::ACCESSKEYSECRET."&",true);
    return base64_encode($str);
  }

  public function pretchStr(string $str){
    $res = urlencode($str);
    $res = preg_replace("/\+/","%20",$res);
    $res = preg_replace("/\*/","%2A",$res);
    $res = preg_replace("/\%7E/","~",$res);
    return $res;
  }
}